package cn.rokhdelar.umbrsapi.management.controller;

import cn.rokhdelar.umbrsapi.management.entity.SysUser;
import cn.rokhdelar.umbrsapi.management.service.SysUserService;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/management/users")
public class SysUserController {
    private final SysUserService sysUserService;

    public SysUserController(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @PostMapping(value = "/{id}/setPassword")
    public Boolean setPassword(@PathVariable Long id, @RequestBody JSONObject param) {
        String newPassword = param.getString("newPassword");
        String repeatNewPassword = param.getString("repeatNewPassword");
        return sysUserService.setPassword(id, newPassword, repeatNewPassword);
    }

    @PostMapping(value = "/{id}/changePassword")
    public ResponseEntity<String> changePassword(@PathVariable Long id, @RequestBody JSONObject param) {
        String oldPassword = param.getString("oldPassword");
        String newPassword = param.getString("newPassword");
        String repeatNewPassword = param.getString("repeatNewPassword");

        return sysUserService.changePassword(id, oldPassword, newPassword, repeatNewPassword);
    }

    @GetMapping
    public Page<SysUser> list(@RequestParam(value = "name", defaultValue = "") String name,
                              @RequestParam(value = "current", defaultValue = "0") Integer current,
                              @RequestParam(value = "size", defaultValue = "20") Integer size) {
        PageRequest pageRequest = PageRequest.of(current, size);
        return sysUserService.listAllByUsername(name, pageRequest);
    }

    @GetMapping(value = "/{id}")
    public SysUser get(@PathVariable Long id) {
        return sysUserService.get(id);
    }

    @PostMapping
    public SysUser create(@RequestBody SysUser sysUser) {
        return sysUserService.create(sysUser);
    }

    @PatchMapping(value = "/{id}")
    public SysUser update(@PathVariable Long id, @RequestBody SysUser sysUser) {
        return sysUserService.update(id, sysUser);
    }

    @DeleteMapping(value = "/{id}")
    public void remove(@PathVariable Long id) {
        sysUserService.delete(id);
    }
}
